package concurrecy;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

class LiftOffRunner implements Runnable {

    private BlockingQueue<LiftOff> queue;

    public LiftOffRunner(BlockingQueue<LiftOff> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while(true) {
                System.out.println("take a lift off ...");
                LiftOff liftOff = queue.take();
                System.out.println("gain a left off, run it");
                liftOff.run();
            }
        } catch (InterruptedException e) {
            System.out.println("runner InterruptedException");
        }
    }
}

/**
 * 阻塞队列
 */
public class BlockingQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<LiftOff> queue = new SynchronousQueue<>();
        Thread thread = new Thread(new LiftOffRunner(queue));
        thread.start();

        for (int i = 0; i < 5; i++) {
            System.out.println("add a lift off");
            try {
                queue.put(new LiftOff());
            } catch (InterruptedException e) {
                System.out.println("main InterruptedException");
            }
        }

        TimeUnit.SECONDS.sleep(2);
        System.out.println("thread.interrupt");
        thread.interrupt();
    }
}
